/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cliente.TwiterApiCliente;

import cliente.domain.Status;
import java.net.URISyntaxException;
import java.util.logging.Level;
import java.util.logging.Logger;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import cliente.gui.Erro;
import cliente.responsehandler.xml.XmlUserTweetsResponseHandler;
import java.net.URI;
import cliente.domain.User;
import cliente.responsehandler.xml.XmlSearchResponseHandler;
import cliente.responsehandler.xml.XmlUserFolloingFollowersHandler;
import java.awt.Desktop;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Vector;
import oauth.signpost.OAuth;
import oauth.signpost.OAuthProvider;
import oauth.signpost.basic.DefaultOAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.exception.OAuthNotAuthorizedException;
import oauth.signpost.signature.SignatureMethod;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;

/**
 *
 * @author Daniel
 */
public class TwitterApiClientOAuth extends TwitterApiClient {

    private CommonsHttpOAuthConsumer consumer = null;
    private OAuthProvider provider = null;

    public TwitterApiClientOAuth(){
         super();
    }

    public void oAuth() {
        try {
            String consumerKey = "SEAqLzIozpYpMVKjirKuA";
            String consumerSecret = "pBiv99audpUxyFKy7AEhYNLq5ohxvBxWSPn4EbqLg";
            String requestTokenURL = "http://twitter.com/oauth/request_token";
            String accessTokenURL = "http://twitter.com/oauth/access_token";
            String authorizeURL = "http://twitter.com/oauth/authorize";

            this.consumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret, SignatureMethod.HMAC_SHA1);
            this.provider = new DefaultOAuthProvider(consumer, requestTokenURL, accessTokenURL, authorizeURL);
            String authURL = this.provider.retrieveRequestToken(OAuth.OUT_OF_BAND);

            Desktop desktop = Desktop.getDesktop();
            URI authorization_page = new URI(authURL);
            desktop.browse(authorization_page);

        } catch (OAuthNotAuthorizedException ex) {
            Logger.getLogger(TwitterApiClientOAuth.class.getName()).log(Level.SEVERE, null, ex);
        } catch (OAuthCommunicationException ex) {
            Logger.getLogger(TwitterApiClientOAuth.class.getName()).log(Level.SEVERE, null, ex);
        } catch (URISyntaxException ex) {
            Logger.getLogger(TwitterApiClient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(TwitterApiClient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (OAuthMessageSignerException ex) {
            Logger.getLogger(TwitterApiClient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (OAuthExpectationFailedException ex) {
            Logger.getLogger(TwitterApiClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void continueOAuth(){
        try {
            String pinCode = gestor.getArquivador().getPassword();
            System.out.println("PIN: "+pinCode);
            this.provider.retrieveAccessToken(pinCode);
            this.gestor.getArquivador().setOAuthToken(consumer.getToken());
            this.gestor.getArquivador().setOAuthTokenSecret(consumer.getTokenSecret());
        } catch (OAuthMessageSignerException ex) {
            Logger.getLogger(TwitterApiClient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (OAuthNotAuthorizedException ex) {
            Logger.getLogger(TwitterApiClient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (OAuthExpectationFailedException ex) {
            Logger.getLogger(TwitterApiClient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (OAuthCommunicationException ex) {
            Logger.getLogger(TwitterApiClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void doXmlRequestWithCredentials(String tipo) {
        HttpGet request = null;

        String reqType = null;

        if ("followers".equalsIgnoreCase(tipo)) {
            reqType = "GET";
            request = new HttpGet("http://twitter.com/statuses/followers/" + gestor.getArquivador().getNickname() + ".xml");
        }
        if ("following".equalsIgnoreCase(tipo)) {
            reqType = "GET";
            request = new HttpGet("http://twitter.com/statuses/friends/" + gestor.getArquivador().getNickname() + ".xml");
        }
        if ("followers".equalsIgnoreCase(tipo)) {
            reqType = "GET";
            request = new HttpGet("http://twitter.com/statuses/followers/" + gestor.getArquivador().getNickname() + ".xml");
        }
        if ("lista_tweets".equalsIgnoreCase(tipo)) {
            reqType = "GET";
            request = new HttpGet("http://twitter.com/statuses/friends_timeline/" + gestor.getArquivador().getNickname() + ".xml");
        }


        /*
         * -----------------------------------
         *      Metodos de GET
         * -----------------------------------
         */

        if (reqType.equals("GET")) {
            if ("followers".equalsIgnoreCase(tipo) || "following".equalsIgnoreCase(tipo)) {
                try {
                    this.consumer.sign(request);
                    ResponseHandler<Vector<User>> responseH = new XmlUserFolloingFollowersHandler(erros);
                    Vector<User> resposta = null;
                    try {
                        resposta = this.httpClient.execute(request, responseH);
                    } catch (IOException e) {
                        System.err.println("Failed to execute GET to " + request.getURI());
                    }
                    if (resposta != null) {
                        gestor.getArquivador().setErro(false);
                        String[] aux = new String[resposta.size()];
                        for (int i = 0; i < resposta.size(); i++) {
                            aux[i] = resposta.get(i).getScreenName();
                        }
                        if ("followers".equalsIgnoreCase(tipo)) {
                            gestor.getArquivador().setFollowers(aux);
                        }
                        if ("following".equalsIgnoreCase(tipo)) {
                            gestor.getArquivador().setFollowing(aux);
                        }
                    }
                } catch (OAuthMessageSignerException ex) {
                    Logger.getLogger(TwitterApiClientOAuth.class.getName()).log(Level.SEVERE, null, ex);
                } catch (OAuthExpectationFailedException ex) {
                    Logger.getLogger(TwitterApiClientOAuth.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            if ("lista_tweets".equalsIgnoreCase(tipo)) {
                try {
                    this.consumer.sign(request);
                    ResponseHandler<Vector<Status>> responseHandler = new XmlUserTweetsResponseHandler(erros);
                    Vector<Status> resposta = null;
                    try {
                        resposta = this.httpClient.execute(request, responseHandler);
                    } catch (IOException e) {
                        System.err.println("Failed to execute GET to " + request.getURI());
                        gestor.getArquivador().setErro(true);
                        Erro erro = new Erro(e.getMessage());
                        erro.setVisible(true);
                    }
                    if (resposta != null) {
                        gestor.getArquivador().setErro(false);
                        Status[] aux = new Status[resposta.size()];
                        for (int i = 0; i < resposta.size(); i++) {
                            aux[i] = resposta.get(i);
                        }
                        gestor.getArquivador().setTweets(aux);
                    }
                } catch (OAuthMessageSignerException ex) {
                    Logger.getLogger(TwitterApiClientOAuth.class.getName()).log(Level.SEVERE, null, ex);
                } catch (OAuthExpectationFailedException ex) {
                    Logger.getLogger(TwitterApiClientOAuth.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

     public void doXmlRequestWithCredentialsAndLotsOfParametersAndWithAFunctionThatIsSupposedToDoStuffThatWeDontKnowYet(String tipo, String cenas) {

        HttpGet request = null;
        HttpPost postReq = null;

        String reqType = null;

        if ("unfollow".equalsIgnoreCase(tipo)) {
            reqType = "POST";
            postReq = new HttpPost("http://twitter.com/friendships/destroy/" + cenas + ".xml");
        }
        if ("follow".equalsIgnoreCase(tipo)) {
            reqType = "POST";
            postReq = new HttpPost("http://twitter.com/friendships/create/" + cenas + ".xml");
        }
        if ("search".equalsIgnoreCase(tipo)) {
            reqType = "GET";
            try {
                request = new HttpGet("http://api.twitter.com/1/users/search.xml?q=" + URLEncoder.encode(cenas, "UTF-8"));
                System.out.println("URL" + request.getURI());
            } catch (UnsupportedEncodingException ex) {
//                Logger.getLogger(TwitterApiClient.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if ("detalhes".equalsIgnoreCase(tipo)) {
            reqType = "GET";
            request = new HttpGet("http://twitter.com/users/show.xml?screen_name=" + cenas);
        }
        if ("lista_tweets".equalsIgnoreCase(tipo)) {
            reqType = "GET";
            try {
                request = new HttpGet("http://twitter.com/statuses/user_timeline.xml?screen_name=" + URLEncoder.encode(cenas, "UTF-8"));
            } catch (UnsupportedEncodingException ex) {
                //Logger.getLogger(TwitterApiClient.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if ("tweet".equalsIgnoreCase(tipo)) {
            try {
                reqType = "POST";
                postReq = new HttpPost("http://twitter.com/statuses/update.xml?status=" + URLEncoder.encode(cenas, "UTF-8"));
            } catch (UnsupportedEncodingException ex1) {
                //System.out.println("[ERRO]Encoding Exeption: Problemas na codificacao do ficheiro!!!\n" + ex1.getMessage());
            }
        }


        /*
         * -----------------------------------
         *      Efectuar Metodos de Get
         * -----------------------------------
         */

        if (reqType.equals("GET")) {
            Vector<User> resposta = null;

            if ("search".equalsIgnoreCase(tipo)) {
                try {
                    this.consumer.sign(request);
                    ResponseHandler<Vector<User>> responseH = new XmlUserFolloingFollowersHandler(erros);
                    try {
                        resposta = this.httpClient.execute(request, responseH);
                    } catch (IOException e) {
                        System.err.println("Failed to execute GET to " + request.getURI());
                        e.printStackTrace();
                        //return;
                    }
                    if (resposta != null) {
                        gestor.getArquivador().setErro(false);
                        String[] aux = new String[resposta.size()];
                        User[] aux_pax = new User[resposta.size()];
                        for (int i = 0; i < resposta.size(); i++) {
                            aux[i] = resposta.get(i).getScreenName();
                            aux_pax[i] = resposta.get(i);
                        }
                        gestor.getArquivador().setPesquisa(aux_pax);
                        gestor.getArquivador().setNomes(aux);
                    }
                } catch (OAuthMessageSignerException ex) {
                    Logger.getLogger(TwitterApiClientOAuth.class.getName()).log(Level.SEVERE, null, ex);
                } catch (OAuthExpectationFailedException ex) {
                    Logger.getLogger(TwitterApiClientOAuth.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            /*
             * -----------------------------------
             *      Listar Tweets
             * -----------------------------------
             */

            if ("lista_tweets".equalsIgnoreCase(tipo)) {
                try {
                    this.consumer.sign(request);
                    ResponseHandler<Vector<Status>> responseHandler = new XmlSearchResponseHandler(erros);
                    Vector<Status> tweets = null;
                    try {
                        tweets = this.httpClient.execute(request, responseHandler);
                    } catch (IOException e) {
                        System.err.println("Failed to execute GET to " + request.getURI());
                        //e.printStackTrace();
                        //return;
                    }
                    if (tweets != null) {
                        System.out.println("---Mensagem---" + tweets.size());
                        Status[] array = new Status[tweets.size()];
                        for (int i = 0; i < tweets.size(); i++) {
                            //System.out.println(i + " - " + tweets.get(i).getText());
                            array[i] = tweets.get(i);
                        }
                        gestor.getArquivador().setListaTweets(array);
                        //System.out.println("Updated---");
                    }
                } catch (OAuthMessageSignerException ex) {
                    Logger.getLogger(TwitterApiClientOAuth.class.getName()).log(Level.SEVERE, null, ex);
                } catch (OAuthExpectationFailedException ex) {
                    Logger.getLogger(TwitterApiClientOAuth.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

        }

        /*
         * -----------------------------------
         *      Efectuar Metodos de Post
         * -----------------------------------
         */

        try {
            if (reqType.equals("POST")) {
                this.consumer.sign(postReq);
                BasicResponseHandler responseHandler = new BasicResponseHandler();
                String coiso = this.httpClient.execute(postReq, responseHandler);
            }
        } catch (OAuthMessageSignerException ex) {
            Logger.getLogger(TwitterApiClientOAuth.class.getName()).log(Level.SEVERE, null, ex);
        } catch (OAuthExpectationFailedException ex) {
            Logger.getLogger(TwitterApiClientOAuth.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException e) {
            //System.out.println("[ERRO]:" + e.getMessage());
            if("tweet".equalsIgnoreCase(tipo)){
                gestor.getArquivador().adicionaSms(cenas);
            }
            gestor.getArquivador().setErro(true);
            Erro erro = new Erro(e.getMessage());
            erro.setVisible(true);
        }
    }
}
